﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace UnitSoftware.LINQ2SQLExtentions
{
    public class DataContextManager
    {
        public readonly static DataContextManager INSTANCE = new DataContextManager();
        //public event EventHandler<DataChangesEventArgs> OnSubmitChanges;

        private List<ManagedDataContext> _dataContexts = new List<ManagedDataContext>();
        private readonly object _registerLock = new object();
        private bool _suppressSynchronize = false;

        public void RegisterDataContext(ManagedDataContext context)
        {
            lock (_registerLock)
            {
                if (!_dataContexts.Contains(context))
                {
                    _dataContexts.Add(context);
                    //context.OnSubmitChanges += new EventHandler<DataChangesEventArgs>(context_OnSubmitChanges);
                }
            }
        }

        //public void UnregisterDataContext(ManagedDataContext context)
        //{
        //    lock (_registerLock)
        //    {
        //        if (_dataContexts.Contains(context))
        //        {
        //            _dataContexts.Remove(context);
        //            context.OnSubmitChanges += new EventHandler<DataChangesEventArgs>(context_OnSubmitChanges);
        //        }
        //    }
        //}

        //void context_OnSubmitChanges(object sender, DataChangesEventArgs e)
        //{
        //    lock (_registerLock)
        //    {
        //        if (_suppressSynchronize) return;

        //        _suppressSynchronize = true;

        //        ManagedDataContext[] contexts = new ManagedDataContext[_dataContexts.Count];
        //        _dataContexts.CopyTo(contexts);
        //        ((ManagedDataContext)sender).Synchronize(_dataContexts);

        //        _suppressSynchronize = false;
        //    }
           
        //}             
    }
}
